package main

import (
	"github.com/gorilla/websocket"
	"net/http"
	"github.com/micro/go-web"
	"github.com/micro/cli"
	"github.com/ngaut/log"
	"global/core"
)

var configFile string

const (
	appName = "ws"
	defaultConfigFile = "../../config/config.toml"
)

var upgrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool { return true },
}

func main() {

	service := web.NewService(
		web.Name("go.micro.web.ws"),
		web.Version("latest"),
		web.Flags(cli.StringFlag{
			Name: 		"config",
			Usage: 		"Custom server config file.",
		}),
	)

	if err := initService(service); err != nil {
		log.Fatalf("Fatal error: %s", err)
	}

	service.Handle("/", http.FileServer(http.Dir("html")))

	s := NewServer(
		initContext(),
		service,
	)
	s.Serv()
}

func initContext() *core.Context {
	ctx := core.NewContext()
	ctx.Bootstrap(configFile, appName).Initialize()
	return ctx
}

// 初始化
func initService(service web.Service) error {
	return service.Init(
		web.Action(func(ctx *cli.Context) {
			configFile = ctx.String("config")
			if configFile == "" {
				configFile = defaultConfigFile
			}
		}),
	)
}